﻿
using System.Collections.Generic;
using System;
using BCService.Utils;
using BCCommon;
using BCData.TMS.SpecificServiceType;
using BCDto.TMS.SpecificServiceType;
using BCEntity.TMS.SpecificServiceType;
using BCDto.Sim.Admin.Admin;
using BCData.TMS.SpecificServiceTypeOverWrite;
using BCEntity.TMS.SpecificServiceTypeOverWrite;
using BCData.TMS.Agent.AgentRecord;
using BCEntity.Common.EntityNameConst;
using BCService.Common.Area;
using BCService.TMS.TransportSpecificServiceConfig;
using BCService.TMS.TransportSpecificServiceConfigOverWrite;
using BCData.TMS.TransportSpecificServiceConfigOverWrite;
using System.Linq;
using BCService.MapperProfiles.TMS.SpecificServiceType;

namespace BCService.TMS.SpecificServiceType
{
    public class SpecificServiceTypeService : ISpecificServiceTypeService
    {
        #region var
        private readonly IDatabaseContext databaseContext;
        private readonly ISpecificServiceTypeData specificServiceTypeData;
        private readonly ISpecificServiceTypeOverWriteData specificServiceTypeOverWriteData;
        private readonly IAgentRecordData agentRecordData;
        private readonly IRedisService redisService;
        private readonly IZoneService zoneService;
        private readonly ITransportSpecificServiceConfigOverWriteData  transportSpecificServiceConfigOverWriteData;

        private readonly string key = string.Format("{0}", EntityNameConst.SpecificServiceTypeEntity);
        private readonly string keyView = string.Format("{0}", EntityNameConst.SpecificServiceTypeViewEntity);

        #endregion

        #region 构造函数
        public SpecificServiceTypeService(IZoneService zoneService,
            IRedisService redisService,
            ISpecificServiceTypeData specificServiceTypeData,
            ISpecificServiceTypeOverWriteData specificServiceTypeOverWriteData, 
            IAgentRecordData agentRecordData,
            ITransportSpecificServiceConfigOverWriteData transportSpecificServiceConfigOverWriteData,
            IDatabaseContext databaseContext)
        {
            this.zoneService = zoneService;
            this.redisService = redisService;
            this.agentRecordData = agentRecordData;
            this.specificServiceTypeOverWriteData = specificServiceTypeOverWriteData;
            this.specificServiceTypeData = specificServiceTypeData;
            this.databaseContext = databaseContext;
            this.transportSpecificServiceConfigOverWriteData = transportSpecificServiceConfigOverWriteData;
        }
        #endregion

        #region Add
        public SpecificServiceTypeDto Add(SpecificServiceTypeRequestDto specificServiceTypeRequestDto, AdminDto admin)
        {
            var list =specificServiceTypeData.GetOnlyListAsync(null).GetAwaiter().GetResult();
            if (list.ToList().Count(s => s.SpecificServiceType == specificServiceTypeRequestDto.SpecificServiceType) > 0)
                throw new ArgumentException("特殊服务类型已经存在!");

            if (admin.CompanyId == 1)
            {
                return this.specificServiceTypeData.InsertAsync(new SpecificServiceTypeEntity()
                {
                    SpecificServiceType = specificServiceTypeRequestDto.SpecificServiceType,
                    ServiceTypeName = specificServiceTypeRequestDto.ServiceTypeName,
                    HasRemark = specificServiceTypeRequestDto.HasRemark,
                    ServiceRemark = specificServiceTypeRequestDto.ServiceRemark,
                    Enabled = specificServiceTypeRequestDto.Enabled,
                    CreateAdminId = admin.AdminId,
                    CreateAdminName = admin.FullName,
                    CreateTime = DateTime.Now,
                    EditAdminId = admin.AdminId,
                    EditAdminName = admin.FullName,
                    UpdateTime = DateTime.Now,

                }).GetAwaiter().GetResult().As<SpecificServiceTypeDto>();
            }
            else
            {
                throw new ArgumentException("代理不能添加");
            }
        }
        #endregion

        #region update
        public SpecificServiceTypeDto Update(SpecificServiceTypePutDto specificServiceTypePutDto, AdminDto admin)
        {
            if (admin.CompanyId == 1)
            {
                var orgEntity = specificServiceTypeData.GetEntityAsync(specificServiceTypePutDto.SpecificServiceTypeId).GetAwaiter().GetResult() ?? throw new ArgumentException("找不到要修改的记录!");

                orgEntity.SpecificServiceType = specificServiceTypePutDto.SpecificServiceType;
                orgEntity.ServiceTypeName = specificServiceTypePutDto.ServiceTypeName;
                orgEntity.HasRemark = specificServiceTypePutDto.HasRemark;
                orgEntity.ServiceRemark = specificServiceTypePutDto.ServiceRemark;
                orgEntity.Enabled = specificServiceTypePutDto.Enabled;
                orgEntity.EditAdminId = admin.AdminId;
                orgEntity.EditAdminName = admin.FullName;
                orgEntity.UpdateTime = DateTime.Now;

                this.redisService.DeleteMultipleKey(keyView, false);
                this.redisService.DeleteMultipleKey(key, false);
                return specificServiceTypeData.UpdateAsync(orgEntity).GetAwaiter().GetResult().As<SpecificServiceTypeDto>();
            }
            else
            {
                throw new ArgumentException("代理商暂无权限添加");
            }
        }
        #endregion


        #region 重写开启关闭
        public SpecificServiceTypeDto UpdateEnable(AdminDto admin, int specificServiceTypeId, bool enable)
        {
            if (admin.CompanyId == 1)
            {
                var entity = specificServiceTypeData.GetEntityAsync(specificServiceTypeId).GetAwaiter().GetResult();
                 
                entity.Enabled = enable;
                entity.EditAdminId = admin.AdminId;
                entity.EditAdminName = admin.FullName;
                entity.UpdateTime = DateTime.Now;

                this.redisService.DeleteMultipleKey(keyView, false);
                this.redisService.DeleteMultipleKey(key, false);

                return specificServiceTypeData.UpdateAsync(entity).GetAwaiter().GetResult().As<SpecificServiceTypeDto>();
            }
            else
            {
                throw new ArgumentException("代理商无权限调用此接口!"); 
            }
        }
        #endregion


        #region Delete
        public void Delete(int specificServiceTypeId, AdminDto admin)
        {
            var dto =  GetById(specificServiceTypeId) ?? throw new ArgumentException("找不到要删除的记录!");
            if (transportSpecificServiceConfigOverWriteData.IsUsedSpecificServiceType(dto.SpecificServiceType).GetAwaiter().GetResult())
                throw new ArgumentException("要删除的记录已被运输特殊服务配置使用,不能删除!");

            if (admin.CompanyId == 1)
            {
                databaseContext.BeginTransaction();
                specificServiceTypeData.DeleteAsync(specificServiceTypeId);
                specificServiceTypeOverWriteData.DeleteByFatherIdAsync(specificServiceTypeId);
                databaseContext.Commit();

                this.redisService.DeleteMultipleKey(keyView, false);
                this.redisService.DeleteMultipleKey(key, false);
            }
            else
            {
                throw new Exception("代理人不能删除只能修改!");
            }

        }
        #endregion

        #region GetBySpecificServiceTypeId
        public SpecificServiceTypeDto GetById(int specificServiceTypeId)
        {
            string cacheKey = this.redisService.GetKey(key, specificServiceTypeId);

            var result = this.redisService.TryGet(cacheKey, () =>
            {
                var data = specificServiceTypeData.GetEntityAsync(specificServiceTypeId).GetAwaiter().GetResult();
                return data;

            }
            , TimeSpan.FromDays(1));
            return result.As<SpecificServiceTypeDto>();
        }
        #endregion


        #region GetList  获取特殊服务类型记录--[分页]
        public PageableList<SpecificServiceTypeDto> GetList(AdminDto admin, bool? isEnabled, int pageIndex, int pageSize)
        {
            int fCount = 0;
            IEnumerable<SpecificServiceTypeEntity> fList;

            string cacheKey = this.redisService.GetKey(key, isEnabled, pageIndex, pageSize);

            var result = this.redisService.TryGet(cacheKey, () =>
            {
                (fList, fCount) = specificServiceTypeData.GetListAsync(isEnabled, pageIndex, pageSize).GetAwaiter().GetResult();

                return new PageableList<SpecificServiceTypeDto>()
                {
                    Count = fCount,
                    Items = fList.As<IEnumerable<SpecificServiceTypeDto>>(),
                    PageIndex = pageIndex,
                    PageSize = pageSize,
                    ServerTime = DateTime.Now,
                };

            }, TimeSpan.FromMinutes(30));

            return result;

        }
        #endregion

        public List<SpecificServiceTypeDto> GetOnlyList(bool? isEnable)
        {
            string cacheKey = this.redisService.GetKey(key, isEnable);


            var result = this.redisService.TryGet(cacheKey, () =>
            {
                return specificServiceTypeData.GetOnlyListAsync(isEnable).GetAwaiter().GetResult().As<List<SpecificServiceTypeDto>>();
            }
            , TimeSpan.FromDays(1));
            return result;
        }
    }
}